<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\Cookie;
use think\File;

class Api extends Controller
{	
	public function _initialize(){

        header("Access-Control-Allow-Origin:*"); 
        header("Access-Control-Allow-Headers:content-type"); 
        header("Access-Control-Request-Method:GET,POST,OPTIONS");

  		if(Request::instance()->isOptions()){
			die;
		}
		
 
    }
    //登录
    //获取ajax传过来的账号密码进行匹配
	public function login(){
		$info = input('post.');
		// echo('11');
		// dump($info);die;
		// $info = $_POST['username'];
		$id_card = $info['username'];
		$password = $info['password'];
		// dump($id_card);die;
		$data = model('Api')->check_login($id_card,$password);
		// dump($data);die;
		return $data;
	

	}
	//修改密码
	public function changeLogin(){
		$info = input('post.');
		// dump($info);die;
		$data = Db::name('students')->where('id_card',$info['username'])->find();
		if(!$info){
			return json_encode(['code'=>0,'msg'=>'身份证输入错误']);
		}

		if($info['name'] != $data['username']){
			return json_encode(['code'=>0,'msg'=>'姓名错误']);
		}

		$change = Db::name('students')->where('id_card',$info['username'])->update(['password'=>$info['password']]);

		if(!$change){
			return json_encode(['code'=>0,'msg'=>'修改失败']);
		}

		return json_encode(['code'=>1,'msg'=>'修改成功']);
		// return json_encode($info)

	}
	//主页 查看学生信息
	public function index(){
		$id = input('post.id');
		
		$data = Db::name('students')->where('id',$id)->find();

		return json_encode($data);

	}
	//成绩主页
	public function sroceIndex(){
		$id_card = input('post.id_card');
		$data = Db::name('topic')->where('id_card',$id_card)->select();
		// dump();die;
		if (!$data) {
			return json_encode(array('code'=>0,'msg'=>'该学生暂未进行考试'));
		}
		for ($i=0; $i < count($data); $i++) { 
			$data[$i]['subject_name'] = getSubjectName($data[$i]['subject_id']);
		}
		
		// dump($data);die;
		return json_encode($data);
		
	}
	/**
	 * [showSorce 查看成绩]
	 * @return [type] [description]
	 */
	public function showSorce(){
		$id = input('post.id');
		// dump($id_card);die;
		$data = Db::name('topic')->where('id',$id)->find();
		// dump($data);die;
		if ($data['not_read'] == 0) {
			return json_encode(array('code'=>0,'msg'=>'该学生暂未进行考试'));
		}
		//将major_id 和subject_id 转成名字
		$major_name = getMajorName($data['major_id']);
		$subject_name = getSubjectName($data['subject_id']);

		// 将整合好的名字存入数组
		$data = ['username'=>$data['username'],'class_name'=>$data['class_name'],'major_name'=>$major_name,'subject_name'=>$subject_name,'scroe'=>$data['scroe'],'status'=>$data['status'],'not_read'=>$data['not_read'],'single_scroe'=>$data['single_scroe'],'selection_scroe'=>$data['selection_scroe'],'judge_scroe'=>$data['judge_scroe'],'operation_scroe'=>$data['operation_scroe'],'pathinfo'=>$data['pathinfo']];
		// dump($data);die;
		return json_encode($data);
	}

	//专业
	public function major(){

		$data = Db::name('major')->where('status',1)->field('id')->field("major_name")->select();
		// dump($data);die;
		foreach ($data as $key => $value) {
			$major_id[] = $value['id'];
			$major_name[] = $value['major_name'];
			
		}

		// $major_name = implode(',',$major_name);
		// dump($major_name);die;
		return json_encode($major_name);

	}

	//专业
	public function major2(){
		$id = input('post.major_id');
		$data = Db::name('major')->where('id',$id)->field('id')->field("major_name")->find();
		// dump($data);die;
		
		return json_encode($data);

	}

	// 获取科目名称api
	public function subject(){
		//获取专业id
		$major = input('post.major_id');
		//封装查询条件
		$map['status'] =1;
		$map['major_id'] =$major;
		//查询数据
		$data = Db::name('subject')->where($map)->field('id')->field('major_id')->field("subject_name")->select();
		// echo Db::name('subject')->getLastSql();die;
		// return json_encode($data);
		foreach ($data as $key => $value) {
			// dump($value);
			$subject_id[] = $value['id'];
			//科目名称
			$subject_name[] = $value['subject_name'];
			// dump($subject_name);die;
			$major_id[] = $value['major_id'];
		}
		return json_encode($subject_name);

	}
	//开始考试
	public function exam_start(){
		// $data = Request::instance()->request();
		// $data['id_card'] = '513701200011125217';
		// $data['subject'] =  'jsp';
		// echo json_encode($data);
		if(Request::instance()->isPost()){

			$data = input('post.');
			$is_exam = Db::name('topic')->where('id_card',$data["id_card"])->field('subject_id')->select();
			// dump($is_exam);die;
			// dump($data['subject']);die;
			$test = Db::name('subject')->where('subject_name',$data['subject'])->find();
			// dump($test);die;
			foreach ($is_exam as $key => $value) {
				if($value['subject_id'] == $test['id']){
					return json_encode(array('code'=>0,'msg'=>'已经考过该科目了'));
				}
			}

			$subject_id = Db::name('subject')->where('subject_name',$data['subject'])->field('id')->find();
			

			$single = Db::name('single')->where('subject_id',$subject_id['id'])->select();
			$selection = Db::name('selection')->where('subject_id',$subject_id['id'])->select();
			$judge = Db::name('judge')->where('subject_id',$subject_id['id'])->select();
			$operation = Db::name('operation')->where('subject_id',$subject_id['id'])->select();
			// dump($single);die;
			 
			//随机打乱数组
			shuffle($single);
			shuffle($selection);
			shuffle($judge);
			shuffle($operation);

			if(!$single){
				return json_encode(array('code'=>0,'msg'=>'该科目暂无考题'));
			}
			//取出10条题目
			$single_question = array_slice($single,0,10);
			$selection_question = array_slice($selection,0,10);
			$judge_question = array_slice($judge,0,5);
			$operation_question = array_slice($operation,0,1);

			$data = ['single'=>$single_question,'selection'=>$selection_question,'judge'=>$judge_question,'operation'=>$operation_question];
			// dump($data);die;
			return json_encode($data);
		}else{
			return json_encode(array('code'=>0,'msg'=>'请求失败'));
		}
	}

	//批改 改卷 存入数据库
	public function correcting(){
		if(request()->isPost()){
			$data = input('post.');
			$id = input('post.id');
			$subject = input('post.subject');
			$exam_name = input('post.exam_name/a');
			$single_post = $exam_name['single'];
			$selection_post = $exam_name['selection'];
			$judge_post = $exam_name['judge'];
			$operation_post = $exam_name['operation'];
			// dump($data['selection_key']);die;
			//保存处理结果
			$single_key = array();
			$selection_key = array();
			$judge_key = array();
			$operation_key = array();
			$student_info = Db::name('students')->where('id',$id)->find();
			// dump($student_info);
			//得分
			$single_sroce = 0 ;
			$selection_sroce = 0 ; 
			$judge_sroce = 0 ; 
			$operation_sroce = 0 ;
			$k = 0;
			$doim = array();
			//查找科目id
			$subject_id = Db::name('subject')->where('subject_name',$subject)->where('status',1)->field('id')->find();
			$add_time = date('Y-m-d H:i:s');
			//单选题加入数组
			for ($i=0; $i < count($single_post); $i++) { 
				//加入数组
				array_push($single_key,'single'.$single_post[$i]['id'].'--'.$data['single_key'][$i]);
				//单选一题三分
				if($single_post[$i]['right_key'] == $data['single_key'][$i]){
					$single_sroce += 3;
				}
			}
			
			//多选加入数组
			//1.循环取出各对应的值（多选题的选择的答案在前端处理完才传过来）
			//2.难点：如何去匹配多选题的正确答案，比如数据库的答案是ABC 而你的答案是BCA
			//以下的做法是，先判断你选择的答案跟数据库的答案的长度是否相等，如果相等做进一步判断，
			//如果不等则此题分数为0
			for ($i=0; $i < count($selection_post); $i++) { 
				array_push($selection_key,'selection'.$selection_post[$i]['id'].'--'.$data['selection_key'][$i]);
					// dump($data['selection_key'][$i]);die;
				//左边是正确答案 右边是选择的答案
				if((strlen($selection_post[$i]['right_key']) == count($data['selection_sroce'][$i]))){
								
					$k += 1;
					//遍历用户选择的答案
					for ($j=0; $j < count($data['selection_sroce'][$i]); $j++) { 
						
					if(is_bool(strpos($selection_post[$i]['right_key'],$data['selection_sroce'][$i][$j]))){
						$doim[$i][$j] = 'false';
					}
			
					}

				}
				
			}
			//答案长度相等的数量 - 答案里面有false的数量
			$k = $k - count($doim);
			//每题四分
			$selection_sroce = $k *4;
			
			//循环取出判断题答案
			for ($i=0; $i < count($judge_post); $i++) { 
				array_push($judge_key,'judge'.$judge_post[$i]['id'].'--'.$data['judge_key'][$i]);
				//判断一题两分
				if($judge_post[$i]['right_key'] == $data['judge_key'][$i]){
					$judge_sroce += 2;
				}
			}

			for ($i=0; $i < count($operation_post); $i++) { 
				array_push($operation_key,'operation'.$operation_post[$i]['id'].'--'.$data['operation_key'][$i]);
				//判断一题两分
				// if($operation_post[$i]['right_key'] == $data['operation_key'][$i]){
				// 	$operation_sroce += 20;
				// }
			}

			// dump($data['operation_key']);die;

			//总分
			$sroce = $single_sroce + $selection_sroce + $judge_sroce + $operation_sroce;
			//分割数组为字符串
			$single = implode(',',$single_key);
			$selection = implode(',',$selection_key);
			$judge = implode(',',$judge_key);
			$operation = implode(',',$operation_key);
			//封装要插入的数据
			$data2 = [
				'single'=>$single,
				'selection'=>$selection,
				'judge'=>$judge,
				'operation'=>$operation,
				'id_card'=>$student_info['id_card'],
				'username'=>$student_info['username'],
				'class_name'=>$student_info['class_name'],
				'major_id'=>$student_info['major_id'],
				'subject_id'=>$subject_id['id'],
				'add_time'=>$add_time,
				'scroe'=>$sroce,
				'status'=>$student_info['status'],
				'single_scroe'=>$single_sroce,
				'selection_scroe'=>$selection_sroce,
				'judge_scroe'=>$judge_sroce,
				'operation_scroe'=>$operation_sroce
			];
			//插入数据库
			$info = Db::name('topic')->insert($data2);
			// echo Db::name('topic')->getLastSql();
			if ($info) {
			return json_encode(array('code'=>1,'msg'=>'提交成功'));
		}
		
		}else{
			echo "11111111111";
		}

	}

	/*
	查看错题
	思路： 1.先获取前端传过来的考卷id值，并查出对应试卷
		  2.将对应题型的题目id跟选择的答案进行分割，然后对题目表进行匹配题目
		  3.依次将匹配的题目存入数组，封装好数组之后将数据返回	
	*/

	public function showError(){
		if(request()->isPost()){
			$id = input('post.id');
			$data = Db::name('topic')->where('id',$id)->find();

			if(!$data){
				return json_encode(array('code'=>0,'msg'=>'服务器开小差啦，请退出重试'));	
			}
			if ($data['single'] == '检测作弊，成绩不合格') {
				return json_encode(array('code'=>0,'msg'=>'考试作弊'));	
			}
			// 定义单选题数组
			$single = array();
			$single_key = array();

			// 定义多选题数组
			$selection = array();
			$selection_key = array();
			//判断题
			$judge = array();
			$judge_key = array();
			//判断题
			$operation = array();
			$operation_key = array();
			$operation_key2 = array();

			$single_all = explode(',', $data['single']);
			//分割多选题
			$selection_all = explode(',', $data['selection']);
			// dump($selection_all);die;
			$judge_all = explode(',', $data['judge']);
			// dump($judge_all);die;
			$operation_all = explode(',', $data['operation']);
			// dump($operation_all);die;
			
			//遍历出单选题的题目跟学生选择的答案
			foreach ($single_all as $key => $value) {
				// explode('--', $value)[0])[1] 题目的ID
				$single[$key] = Db::name('single')->where('id',explode('single',explode('--', $value)[0])[1])->find();
				// $single[$key] = explode('single',explode('--', $value)[0])[1];
				$single_key[$key] = explode('--', $value)[1];
				// dump(explode('--', $value)[1]);die;
			}
			// dump($single);die;

			//遍历出多选题的题目跟学生选择的答案
			foreach ($selection_all as $key => $value) {
				$selection[$key] = Db::name('selection')->where('id',explode('selection',explode('--', $value)[0])[1])->find();
				// $single[$key] = explode('single',explode('--', $value)[0])[1];
				$selection_key[$key] = explode('--', $value)[1];
			}
			// dump($selection_key);
			// dump($selection);die;
			
			foreach ($selection_key as $key => $value) {
				$selection_key2[$key] = preg_split('//',$selection_key[$key],-1,PREG_SPLIT_NO_EMPTY);
			}
			// dump($selection_key2);die;


			//遍历出多选题的题目跟学生选择的答案
			foreach ($judge_all as $key => $value) {
				$judge[$key] = Db::name('judge')->where('id',explode('judge',explode('--', $value)[0])[1])->find();
				// $single[$key] = explode('single',explode('--', $value)[0])[1];
				$judge_key[$key] = explode('--', $value)[1];
			}
			// dump($judge_key);
			// dump($judge);die;
			//遍历出多选题的题目跟学生选择的答案
			foreach ($operation_all as $key => $value) {
				$operation[$key] = Db::name('operation')->where('id',explode('operation',explode('--', $value)[0])[1])->find();
				// $single[$key] = explode('single',explode('--', $value)[0])[1];
				$operation_key[$key] = explode('--', $value)[1];
			}
			// dump($operation_key);
			// dump($operation);die;
			

			$info = ['single'=>$single,'selection'=>$selection,'judge'=>$judge,'operation'=>$operation,'single_key'=>$single_key,'selection_key'=>$selection_key,'selection_key2'=>$selection_key2,'judge_key'=>$judge_key,'operation_key'=>$operation_key];

			return json_encode($info);

		}else{
			echo "不是ajax";
		}
		
	}
	/*
	每日一练
	思路：
	    1.获取题库里面的题目，将其打乱
	    2.将题目构造成数组，传给前端
	    3.因为是每日练习，所以不存入数据库

	*/
	public function practice(){
		$data = input('post.');

		// dump($data);die;
		$subject_id = Db::name('subject')->where('subject_name',$data['subject'])->field('id')->find();
		// dump($subject_id);die;
		$single = Db::name('single')->where('subject_id',$subject_id['id'])->select();
		$selection = Db::name('selection')->where('subject_id',$subject_id['id'])->select();
		$judge = Db::name('judge')->where('subject_id',$subject_id['id'])->select();
		$operation = Db::name('operation')->where('subject_id',$subject_id['id'])->select();
		// dump($single);die;
		 
		//随机打乱数组
		shuffle($single);
		shuffle($selection);
		shuffle($judge);
		shuffle($operation);

		if(!$single){
			return json_encode(array('code'=>0,'msg'=>'该科目暂无考题'));
		}
		//截取数组： array_slice(数组,截取位置,截取长度)
		$single_question = array_slice($single,0,4);
		$selection_question = array_slice($selection,0,4);
		$judge_question = array_slice($judge,0,2);
		// $operation_question = array_slice($operation,0,1);

		$data = ['single'=>$single_question,'selection'=>$selection_question,'judge'=>$judge_question];

		return json_encode($data);
	}
	

	//聊天
	public function chat(){
		$data = input('post.');
		$add_time = date('Y-m-d H:i:s');
		$data = ['username'=>$data['username'],'content'=>$data['sms'],'add_time'=>$add_time];
		$info = Db::name('chat')->insert($data);
		if ($info) {
			return json_encode(array('code'=>1,'msg'=>'留言成功'));
		}
	}
	//获取聊天信息
	public function getChat(){
		$data = Db::name('chat')->select();
		return json_encode($data);
	}

	public function ranking(){

	    $id = input('post.id');
	    $subject_id = Db::name('topic')->where('id',$id)->field('subject_id')->find();
	    // var_dump($id);
	    // var_dump($subject_id);
	    // $data = Db::name('topic')->where('subject_id',$subject_id['subject_id'])->where('not_read',1)->

	    // $exam_paper = input('post.exam_paper');
	 //    $subject_id = Db::name('topic')->where('id',$exam_paper)->field('subject_id')->find();
	 //    // dump($exam_paper);die;
		$data = Db::name('topic')->where('subject_id',$subject_id['subject_id'])->where('not_read',1)->order('scroe desc')->field('scroe')->field('username')->field('class_name')->field('id_card')->limit(5)->select();
		// var_dump($data);
		foreach ($data as $key => $value) {
			$data[$key]['img'] = Db::name('students')->where('id_card',$value['id_card'])->field('img')->find()['img'];
		}
		// dump($data);die;
		if (!$data) {
			return json_encode(array('code'=>0,'msg'=>'排行榜开小差啦'));
		}
		// dump($data);die;
		return json_encode($data);
		
	}

	public function video(){

		$data = file_get_contents(ROOT_PATH.'/'.'public/video/video.txt');
		$rep = str_replace("\r\n",',',$data);
		$ex_video = explode(',',$rep);
		// dump($video);die;
		shuffle($ex_video);
		
		//取出10条题目
		$video1 = array_slice($ex_video,0,8);
		$video2 = array_slice($ex_video,5,4);
		$video3 = array_slice($ex_video,10,4);
		$list = ['video1'=>$video1,'video2'=>$video2,'video3'=>$video3];
		return json_encode($video1);
	}
// 可查阅书籍
	public function book(){
		// $data = file_get_contents("");
		// $re = json_decode($data,true);
		
		// return json($re);
		
		$data = Db::name('book_info')->where('status',1)->select();

		if (!$data) {
			return json_encode(array('code'=>0,'msg'=>'服务器开小差啦'));
		}

		foreach ($data as $key => $value) {
			
			$data[$key]['category_name'] = getCategoryName($value['category_id']);
		}
		shuffle($data);
		// dump($data);die;
		return json_encode($data);
	}

	//热门推荐
	public function recommend(){
		$data = Db::name('book_info')->where('status',1)->select();
		if (!$data) {
			return json_encode(array('code'=>0,'msg'=>'服务器开小差啦'));
		}
		shuffle($data);
		$slice_data = array_slice($data,0,10);

		return json_encode($slice_data);
	}
// 书籍分类
	public function category_book(){
		$data = Db::name('category')->where('status',1)->select();

		return json_encode($data);
	}
// 获取书籍详情
	public function book_detail(){
		$id = input('post.id');

		$data = Db::name('book_info')->where('id',$id)->find();

		if (!$data) {
			return json_encode(array('code'=>0,'msg'=>'服务器开小差啦'));
		}
		$data['category_name'] = getCategoryName($data['category_id']);
		return json_encode($data);
	}
// 搜索
	public function book_search(){
		$data = Db::name('book_info')->where('status',1)->select();
		shuffle($data);
		if (!$data) {
			return json_encode(array('code'=>0,'msg'=>'服务器开小差啦'));
		}

		return json_encode($data);
	}
	//发表评论
	public function book_comment(){
		$sms = input('post.sms');
		$id_card = input('post.id_card');
		$book_id = input('post.book_id');
		$student = Db::name('students')->where('id_card',$id_card)->field('username')->field('id_card')->find();
		// dump($student);die;
		$data = ['username'=>$student['username'],'id_card'=>$student['id_card'],'content'=>$sms,'book_id'=>$book_id,'add_time'=>date('Y-m-d H:i:s')];
		 
		$info = Db::name('comment')->insert($data);

		if (!$info) {
			return json_encode(array('code'=>0,'msg'=>'评论失败'));
		}else{
			return json_encode(array('code'=>1,'msg'=>'评论成功'));
		}
	}

	//获取评论信息
	public function comment(){
		$book_id = input('post.id');
		$data = Db::name('comment')->where('book_id',$book_id)->where('status',1)->order('id asc')->select();

		if (!$data) {
			return json_encode(array('code'=>0,'msg'=>'服务器开小差啦'));
		}

		return json_encode($data);

	}
	// 获取书籍内容
	public function catalog(){
		$id = input('post.id');
		$data = Db::name('chapter')->where('book_id',$id)->order("chapter_id asc")->select();
		return json_encode($data);
	}
	// 在详情页面点击阅读时去判断书架上是否有这本书
	public function show_book(){
		$data = input('post.');
		$k=Db::name('bookshelf')->where('username',$data['username'])->find();
		// return json_encode($data);
		// var_dump($k);
		$infobook = [];
		// 将字符串转换为数据
		$book_id = explode(',',$k['book_id']);
		$read_history = explode(',',$k['read_history']);
		if (in_array($data['book_id'],$book_id)) {
			//取出改书拆分
				for($i=0; $i < count($read_history)-1;$i++){
					//拆分书本和阅读记录
					$ex_book_read = explode('-',$read_history[$i]);	
					// 判断书id取章节
					if((int)$ex_book_read[0] == (int)$data['book_id']){
						// 
						 $infobook['read_history']=$ex_book_read[1];

					}else{

					}
				}

		}else{
			// 书架上没有书时
			$infobook['read_history']= -1;
		}
		return json_encode($infobook);
	}


	/*
	阅读
	思想
	 1.获取传过来的书本
	 2.判断本书是否在书架中，如果不在书架就直接从第一章开始阅读
	 3.如果本书本书在书架就要读取书架上存的阅读记录，并且判断他是否是直接在详情页从目录跳转的，立即阅读是直接取阅读记录，跳转是读的跳转章节；如果在书架就直接读取历史记
	 总结：总觉得自己逻辑有问题这一块写的不太好，如果有更好的方法可以给予联系
	 	邮箱：1904617853@qq.com
	 */

	public function read_book(){
		
		$data = input('post.');
		// dump($data);die;
		$read_history_id = -1;//定义一个初始值（）
		$test = Db::name('bookshelf')->where('username',$data['username'])->find();
		$book_ids = explode(',',$test['book_id']);
		//判断本书是否在书架上
		if(in_array($data['book_id'],$book_ids)){
			if(!$data['chapter_id'] == -1){
				//判断是第一次获取还是上下章
				if($data['username'] !== 404) {
					// dump($data['username']);die;
					
					$read_history_list = explode(',',$test['read_history']);
					foreach ($read_history_list as $key => $value) {
						$book_read_history = explode('-',$read_history_list[$key]);
						// dump($book_read_history);die;
						if($book_read_history[0] == $data['book_id']){
							$read_history_id = $book_read_history[1];
						}
					}			
				}
			}else{

				$read_history_id = $data['chapter_id'];
			}


		}else{
			if($data['chapter_id'] == -1){
				if($data['username'] !== 404) {
					$read_history_id = 1;
				}
			}
		}
		//查询最后一章
		$k = Db::name('chapter')->where('book_id',$data['book_id'])->order("chapter_id asc")->select();
		if (!$k) {
			return json_encode(array('codes'=>0,'msg'=>'该书章节未上传'));
		}
		$is_null = array_slice($k,-1,1);
		
		
		//三目运算 判断是上下章还是初始化
		$read_history_id = $read_history_id !== -1? $read_history_id : $data['chapter_id'];

		
		$readData = Db::name('chapter')->where('book_id',$data['book_id'])->order("chapter_id asc")->where('chapter_id',$read_history_id)->find();

		//最后一章 进行数据处理
		if($is_null[0]['chapter_id'] == $data['chapter_id']){
			$readData['code'] = 0;
		}
		
		$readData['chapter_id'] = $read_history_id;
		//解析数据库得书本内容
		$readData['content'] = stripcslashes(htmlspecialchars_decode($readData['content']));
		
		return json_encode($readData);
	}
	/*
	记录阅读进度
	思想：
	 1.获取过来的数据，先查询数据库里面是否有这个书架
	 2.如果有这个书架说明，他之前有将本书加入书架，所以就要对阅读进度进行记录
	 3.假如没有书架就不进行记录操作
	 */
	public function read_hirstory(){
		$data = input('post.');
		// dump($data);die;
		
		$book_id_str = '';
		$read_history_str = '';
		// 查询该用户有无书架
		$k = Db::name('bookshelf')->where('username',$data['id_card'])->find();	
		if ($k){
			//将字符串转成数组
			$book_id = explode(',',$k['book_id']);
			$read_history = explode(',',$k['read_history']);
			//判断本书是否在书架中
			if(in_array($data['book_id'],$book_id)){
				//取出数据库的阅读记录字段进行遍历
				for($i=0; $i < count($read_history)-1;$i++){
					//拆分书本和阅读记录
					$ex_book_read = explode('-',$read_history[$i]);
					
					// return json_encode($ex_book_read);
					// 拿拆分完的书本匹配传过来的书本 如果相等替换他的阅读进度，如果不等按原来的拼接
					if((int)$ex_book_read[0] == (int)$data['book_id']){
						//将旧的阅读进度替换成新的
						(int)$ex_book_read[1] = (int)$data['chapter_id'];
						//拼接好阅读记录
						$read_history_str = $read_history_str.(int)$ex_book_read[0].'-'.$ex_book_read[1].',';
						
					}else{
						// dump($ex_book_read[1]);die;
						$read_history_str = $read_history_str.$ex_book_read[0].'-'.$ex_book_read[1].',';
						// dump($ex_book_read[1]);die;
					}
			  
				}
				
			}else{

				$read_history_str = $k['read_history'];

				
			}			
			$info = Db::name('bookshelf')->where('username',$data['id_card'])->update(['read_history'=>$read_history_str]);
		}else{

		}
		
	}
	/*
	 添加到书架
	 */
	public function add_bookshelf(){
		$data = input('post.');
		// dump($data);die;
		$k = Db::name('bookshelf')->where('username',$data['username'])->where('status',1)->find();
		// dump($k);die;
		if($k){	
			$book_id = explode(',',$k['book_id']);
			$read_history = explode(',',$k['read_history']);
			//删除最后一个逗号带来的元素
			array_pop($read_history);
			if(in_array($data['id'],$book_id)){
				return json_encode(array('code'=>0,'msg'=>'书架上已经有这本书啦！'));
			}
			// dump($book_id);
			//往数组添加一个元素 然后转成字符串
			array_push($book_id,$data['id']);
			// dump($book_id);die;
			$book_id_str = implode(',',$book_id);
			// dump($book_id_str);die;
			
			$add_read_history = $data['id'].'-'.'1'.',';
			array_push($read_history,$add_read_history);
			$read_history_str = implode(',',$read_history);
			// dump($read_history_str);die;
			$info = Db::name('bookshelf')->where('username',$data['username'])->update(['book_id'=>$book_id_str,'read_history'=>$read_history_str]);
			if($info){
				return json_encode(array('code'=>1,'msg'=>'加入成功'));
			}

		}else if(!$k){
		 	$info2 = Db::name('bookshelf')->insert(['username'=>$data['username'],'book_id'=>$data['id'],'read_history'=>$data['id'].'-'.'1'.',']);
		 	if($info2){
				return json_encode(array('code'=>1,'msg'=>'加入成功'));
			}
		}else{
			return json_encode(array('code'=>0,'msg'=>'服务繁忙，请重试'));
		}

		

	}
	// 删除书架上的书
	public function delete_book(){
		// $username =
		$data = input('post.');
		$k =Db::name('bookshelf')->where('username',$data['id_card'])->find();

		$book_id_str = '';
		$read_history_str = '';
		// dump($k);
		if ($k) {
			$book_id = explode(',',$k['book_id']);
			$read_history = explode(',',$k['read_history']);
			// dump($read_history);
			// 判断有无书
			if(in_array($data['book_id'],$book_id)){
				// 查询书架的id
				if (($key = array_search($data['book_id'], $book_id)) !== false) {
					// dump($key);die;	删除id
					unset($book_id[$key]);
					// 保存处理结果
					$book_id_str = implode(',',$book_id);
					
				}
				// 阅读记录
				$data['read_history'] =$data['book_id'].'-'.$data['read_history'];
				// dump($data['read_history']);die;
				if (($key = array_search($data['read_history'], $read_history)) !== false) {
					// dump($key);die;
					unset($read_history[$key]);
					// 保存处理结果
					$read_history_str = implode(',',$read_history);
					// dump($read_history_str);die;
				}
				
			}
			// $info = Db::name('bookshelf')->where('username',$data['id_card'])->update(['read_history'=>$read_history_str]);
			$info = Db::name('bookshelf')->where('username',$data['id_card'])->update(['book_id'=>$book_id_str,'read_history'=>$read_history_str]);

			$k =Db::name('bookshelf')->where('username',$data['id_card'])->find();
			// echo "aaaaaaaaaa";die;
			if($k['book_id']==''){
				$k =Db::name('bookshelf')->where('username',$data['id_card'])->delete();
			}
		}


	}


	/*
	详情页热门推荐
	 */
	public function detail_recommend(){
		$data = Db::name('book_info')->where('status',1)->select();

		shuffle($data);
		$info = array_slice($data,0,4);

		return json_encode($info);

	}
// 查看书架的书籍
	public function show_bookshelf(){
		$data = input('post.');

		$k = Db::name('bookshelf')->where('username',$data['username'])->find();
		// dump($k);die;
		if(!$k){
			return json_encode(array('code'=>0,'msg'=>'书架上还没有书'));
		}

		// if ($k['book_id'] == '' && $k['read_history']== '') {
		// 	return json_encode(array('code'=>0,'msg'=>'书架上还没有书'));
		// }

			  	// echo "不存在";die;
			$book_id = explode(',',$k['book_id']);
			$book_id_list = array();
			$read_history = explode(',',$k['read_history']);

			foreach ($book_id as $key => $value) {
				$book_id_list[$key] = Db::name('book_info')
				->where('id',$value)
				->field('id')
				->field('book_name')
				->field('book_cover')
				->field('writer')
				->find();

				$read_history_list[$key] = explode('-',$read_history[$key]);
				$book_id_list[$key]['read_history'] = $read_history_list[$key][1];

			}
			// dump($book_id_list);die;
			return json_encode($book_id_list);
		
	}

	public function news(){
		$data = Db::name('news')->where("status",1)->select();

		return json_encode($data);
	}

	public function newsindex(){
		$data = input('post.');
		$info = Db::name('news')->where('id',$data['id'])->where("status",1)->find();

		return json_encode($info);
		
	}
	//发布动态 
	public function send_dynamic(){
		$data =input('post.');
		if (strlen($data['content']) > (1024*1024)) {
			return json_encode(array('code'=>0,'msg'=>'发布失败，图片过大'));
		}
        $time = date('Y-m-d H:i:s');
        $list = ["name"=>$data['name'],"username"=>$data['username'],"content"=>$data['content'],"add_time"=> $time];
		$info = Db::name('friend')->insert($list);
		if($info){
			return json_encode(array('code'=>1,'msg'=>'发布成功'));
		}else{
			return json_encode(array('code'=>0,'msg'=>'服务器开小差了,请重新发送'));
		}
	}
	//获取头像
	public function get_head_photo(){
		$username = input('post.username');

		$data = Db::name('students')->where('id_card',$username)->find();
		// dump($data);die;
		return json_encode($data);
	}

	//获取动态
	public function get_dynamic(){

		$data = Db::name('friend')->where('status',1)->order("id desc")->select();
		// dump($data);die;
		foreach ($data as $key => $value) {
			 $img = Db::name("students")->where('id_card',$value['username'])->field('img')->find();
			 $data[$key]['stu_img'] = $img['img'];
		}
		// dump($data);die;
		return json_encode($data);
	}

	//上传头像
	public function up_photo(){
		
		$data = input("post.");
		if(strlen($data['list'][0]['content']) > (700 * 1024)){
			return json_encode(array('code'=>0,'msg'=>'图片过大'));
		}
		// dump($data['username']);die;
		$info = Db::name('students')->where('id_card',$data['username'])->update(['img'=>$data['list'][0]['content']]);
		if($info){
			return json_encode(array('code'=>1,'msg'=>'上传成功'));
		}else{
			return json_encode(array('code'=>0,'msg'=>'服务器开小差了,请重试'));
		}
		// dump($data['list'][0]['content']);die;
		
	}
}